package com.yrh.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yrh.bean.TCart;
import com.yrh.bean.TUser;
import com.yrh.service.TCartService;
import com.yrh.service.impl.TCartServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/*购物车控制层*/
@WebServlet("/CartServlet/*")
public class CartServlet extends BaseServlet{
    private TCartService service=new TCartServiceImpl();
    public void addCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前台的参数封装为JavaBean
        Map<String, String[]> map = request.getParameterMap();
        TCart c=new TCart();
        BeanUtils.populate(c,map);
        //获取用户信息
        TUser user = (TUser) request.getSession().getAttribute("user");
        c.setUserId(user.getUserId());
        //查询购物车中是否存在该商品
        List<TCart> tCarts = service.allCart(c);
        if (tCarts.size()>0){//购物车中存在该商品 修改商品数量 商品数量加一
            c=tCarts.get(0);
            c.setProductNum(c.getProductNum()+1);
            service.save(c);//修改购物车
        }else {
            //添加商品进入购物车
            service.save(c);
        }
    }
    //获取购物车数据
    public void allCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        TCart cart = new TCart();
        //获取用户信息
        TUser user = (TUser) request.getSession().getAttribute("user");
        cart.setUserId(user.getUserId());
        //获取购物车的数据
        List<TCart> list = service.allCart(cart);
        // 转换为json并传递给客户端
        ObjectMapper mapper=new ObjectMapper();
        mapper.writeValue(response.getWriter(),list);

    }
    /*修改购物车数量*/
    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        TCart cart=new TCart();
        BeanUtils.populate(cart,map);
        service.save(cart);
    }
    //删除订单
    public void deleteCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        TCart cart=new TCart();
        BeanUtils.populate(cart,map);
        TUser user = (TUser) request.getSession().getAttribute("user");
        cart.setUserId(user.getUserId());
        service.deleteCart(cart);
    }
}